var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require('fs');
var bodyParser = require('body-parser')
// var template = require ( 'art-template' ); 

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var topage = require('./routes/topage');

var app = express();
var cors = require('cors');
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/topage', topage);





var STS = require('qcloud-cos-sts');
// 配置参数
var config = {
  secretId: 'AKIDb2D8mAI9j36sNbYEdlcCWZLq65nLbaIk',
  secretKey: 'C7l9G6ewxhBOL1QYQ1KM8droUu3vWtzo',
  proxy: '',
  durationSeconds: 1800,

  // 放行判断相关参数
  bucket: 'yanxianfei-1307931282',
  region: 'ap-beijing',
  allowPrefix: '*', // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  // 简单上传和分片，需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
  allowActions: [
      // 简单上传
      'name/cos:PutObject',
      'name/cos:PostObject',
      // 分片上传
      'name/cos:InitiateMultipartUpload',
      'name/cos:ListMultipartUploads',
      'name/cos:ListParts',
      'name/cos:UploadPart',
      'name/cos:CompleteMultipartUpload'
  ],
};

// 腾讯云生成临时秘钥

// 创建临时密钥服务
var app = express();
app.use(bodyParser.json());

// 支持跨域访问
app.all('*', function (req, res, next) {
  res.header('Content-Type', 'application/json');
  res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:88');
  res.header('Access-Control-Allow-Headers', 'origin,accept,content-type');
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method.toUpperCase() === 'OPTIONS') {
      res.end();
  } else {
      next();
  }
});
// 临时密钥接口
app.all('/sts', function (req, res, next) {

  // TODO 这里根据自己业务需要做好放行判断

  // 获取临时密钥
  var shortBucketName = config.bucket.substr(0 , config.bucket.lastIndexOf('-'));
  var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
  var policy = {
      'version': '2.0',
      'statement': [{
          'action': config.allowActions,
          'effect': 'allow',
          'principal': {'qcs': ['*']},
          'resource': [
              'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
          ],
      }],
  };
  STS.getCredential({
      secretId: config.secretId,
      secretKey: config.secretKey,
      proxy: config.proxy,
      durationSeconds: config.durationSeconds,
      policy: policy,
  }, function (err, tempKeys) {
      var result = JSON.stringify(err || tempKeys) || '';
      res.send(result);
  });
});
// app.all('*', function (req, res, next) {
//   res.writeHead(404);
//   res.send({code: 404, codeDesc: 'PageNotFound', message: '404 page not found'});
// });












// catch 404 and forward to error handler
app.use(function(req, res, next) {
    // next(createError(404));
    res.end("not this to pages")
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page

  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
